﻿using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class UDPServer : MonoBehaviour
{
    public string recvStr;
    Socket socket;
    public EndPoint clientEnd;
    public IPEndPoint ipEnd;
    Thread connectThread;

    /// <summary>
    /// 初始化, 服务端IP和端口号port
    /// </summary>
    public void Init(string ip, int port)
    {
        IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse(ip), port);
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.Bind(ipEnd);
        //定义客户端
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
        EndPoint clientEnd = (EndPoint)sender;
        Debug.Log("服务器开启:" + ipEnd);
        //开启一个线程连接
        connectThread = new Thread(new ThreadStart(Receive));
        connectThread.Start();
    }

    /// <summary>
    /// 发送消息msg
    /// </summary>
    public void Send(string msg)
    {
        byte[] data = new byte[1024];
        data = Encoding.UTF8.GetBytes(msg);
        socket.SendTo(data, data.Length, SocketFlags.None, clientEnd);
    }
    //服务器接收
    public void Receive()
    {
        while (true)
        {
            byte[] data = new byte[1024];
            int leng = socket.ReceiveFrom(data, ref clientEnd);
            recvStr = Encoding.UTF8.GetString(data, 0, leng);
            Debug.Log("收到消息!");
            Debug.Log(string.Format("客户端{0}发送信息{1}", recvStr, clientEnd) );
        }
    }

    //连接关闭
    public void Close()
    {
        //关闭线程
        if (connectThread != null)
        {
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭socket
        if (socket != null)
            socket.Close();
        Debug.LogWarning("断开连接");
    }

}
